document.addEventListener('DOMContentLoaded', function () {
    const navLinks = document.querySelectorAll('.nav-link');
    const contentAreas = document.querySelectorAll('.content');

    // 模拟点击第一个带有 active 类的导航链接
    const activeLink = document.querySelector('.nav-link.active');
    if (activeLink) {
        const targetId = activeLink.dataset.target;
        const targetContent = document.getElementById(targetId);
        navLinks.forEach(navLink => navLink.classList.remove('active'));
        contentAreas.forEach(content => content.classList.remove('active'));
        activeLink.classList.add('active');
        if (targetContent) {
            targetContent.classList.add('active');
        }
    }

    navLinks.forEach(link => {
        link.addEventListener('click', function (e) {
            navLinks.forEach(navLink => navLink.classList.remove('active'));
            contentAreas.forEach(content => content.classList.remove('active'));
            this.classList.add('active');
            const targetId = this.dataset.target;
            const targetContent = document.getElementById(targetId);
            if (targetContent) {
                targetContent.classList.add('active');
            }
        });
    });
    const tables = document.querySelectorAll('.adminManagement-table');
    tables.forEach(function (table) {
        const selectAll = table.querySelector('.selectAll');
        const rowCheckboxes = table.querySelectorAll('.rowCheckbox');

        selectAll.addEventListener('change', function () {
            const isChecked = this.checked;
            rowCheckboxes.forEach(function (checkbox) {
                checkbox.checked = isChecked;
            });
        });

        rowCheckboxes.forEach(function (checkbox) {
            checkbox.addEventListener('change', function () {
                const allChecked = Array.from(rowCheckboxes).every(function (cb) {
                    return cb.checked;
                });
                selectAll.checked = allChecked;
            });
        });
    });

    //删除帖子
    $(document).ready(function () {
        $('.deletebtn').click(function (event) {
            event.preventDefault();
            const id = $(this).data('id');
            console.log('获取到的id:', id);
            const $button = $(this); // 保存当前按钮的引用
            if (confirm('确定要删除该文章吗？')) {
                $.ajax({
                    url: `http://localhost:8080/admin/toDeleteCategory`,
                    method: 'GET',
                    data: { id: id }, // 确保参数名称和后端一致
                    dataType: 'text',
                    success: function (response) {
                        $button.closest('tr').remove();
                        console.log(id);
                    },
                    error: function (error) {
                        console.log('删除文章失败:', error);
                        alert('删除文章失败，请重试');
                        console.log(this.url);
                    }
                });
            }
        });

    });

    // 封装打开模态框并填充数据的函数
    function openModalAndFillData(modalId, button) {
        const modal = document.getElementById(modalId);
        modal.style.display = 'block';
        const currentRow = button.closest('tr');
        return currentRow;
    }

    $(document).ready(function () {
        const rowsPerPage = 10; // 每页显示的行数
        const $tableBody = $('#categoryList');
        const rows = $tableBody.find('tr');
        const numPages = Math.ceil(rows.length / rowsPerPage);

        function showPage(pageNumber) {
            const startIndex = (pageNumber - 1) * rowsPerPage;
            const endIndex = startIndex + rowsPerPage;
            rows.hide().slice(startIndex, endIndex).show();

            const $pageNav = $('#pageNav');
            $pageNav.empty();

            for (let i = 1; i <= numPages; i++) {
                const $a = $('<a href="#">').text(i);
                if (i === pageNumber) {
                    $a.addClass('active');
                }
                $a.click(function (e) {
                    e.preventDefault();
                    showPage(i);
                });
                $pageNav.append($a);
            }
        }

        showPage(1);
    });
        $(document).ready(function () {
        const rowsPerPage = 9; // 每页显示的行数
        const $tableBody = $('#categoryList');
        const rows = $tableBody.find('tr');
        const numPages = Math.max(1, Math.ceil(rows.length / rowsPerPage)); // 至少有一页
        let currentPage = 1;

        // 显示指定页的数据
        function showPage(pageNumber) {
        currentPage = pageNumber;
        const startIndex = (pageNumber - 1) * rowsPerPage;
        const endIndex = startIndex + rowsPerPage;

        // 隐藏所有行，然后显示当前页的行
        rows.hide();
        rows.slice(startIndex, endIndex).show();

        // 更新分页导航
        updatePagination();
    }

        // 更新分页导航
        function updatePagination() {
        const $pageNav = $('#pageNav');
        $pageNav.empty();

        // 添加"上一页"按钮
        const $prevBtn = $('<a href="#" class="prev-btn">').text('上一页');
        if (currentPage === 1) {
    } else {
        $prevBtn.click(function (e) {
        e.preventDefault();
        showPage(currentPage - 1);
    });
    }
        $pageNav.append($prevBtn);

        // 添加页码按钮
        // 只显示当前页附近的页码，避免过多按钮
        const maxVisiblePages = 5;
        let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
        let endPage = startPage + maxVisiblePages - 1;

        if (endPage > numPages) {
        endPage = numPages;
        startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }

        // 添加省略号（如果需要）
        if (startPage > 1) {
        $pageNav.append($('<span>').text('...'));
    }

        for (let i = startPage; i <= endPage; i++) {
        const $pageBtn = $('<a href="#" class="num">').text(i);
        if (i === currentPage) {
        $pageBtn.addClass('active');
    } else {
        $pageBtn.click(function (e) {
        e.preventDefault();
        showPage(i);
    });
    }
        $pageNav.append($pageBtn);
    }

        // 添加省略号（如果需要）
        if (endPage < numPages) {
        $pageNav.append($('<span>').text('...'));
    }

        // 添加"下一页"按钮
        const $nextBtn = $('<a href="#" class="next-btn">').text('下一页');
        if (currentPage === numPages) {
        $nextBtn.addClass('disabled');
    } else {
        $nextBtn.click(function (e) {
        e.preventDefault();
        showPage(currentPage + 1);
    });
    }
        $pageNav.append($nextBtn);
    }

        // 初始化页面
        if (rows.length > 0) {
        showPage(1);
    }
    });
        });
const categoryEditModal = document.getElementById('categoryEditModal');
const categoryEditModalSaveButton = document.getElementById('categoryEditModalSaveButton');
let currentCategoryId = null; // 存储当前编辑的类别ID

// 类别编辑按钮事件处理
const editButtons = document.querySelectorAll('.editbtn');
let currentEditRow;
function openModalAndFillData(modalId, button) {
    const modal = document.getElementById(modalId);
    modal.style.display = 'block';
    const currentRow = button.closest('tr');
    return currentRow;
}
editButtons.forEach(function(button) {
    button.addEventListener('click', function() {
        currentEditRow = openModalAndFillData('categoryEditModal', this);
        // 直接从按钮的data-id属性获取id
        currentCategoryId = this.getAttribute('data-id');
        console.log('获取到的类别ID:', currentCategoryId); // 添加日志确认


        // 填充数据到模态框
        // 填充数据到模态框
        const name = currentEditRow.querySelector('td:nth-child(2)').textContent;
        const title = currentEditRow.querySelector('td:nth-child(3)').textContent;
        const contentCell = currentEditRow.querySelector('td:nth-child(4)');
        let content = contentCell.innerHTML;
        const kind = currentEditRow.querySelector('td:nth-child(5)').textContent;

        // 去除 .contents 类
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = content;
        const contentsDiv = tempDiv.querySelector('.contents');
        if (contentsDiv) {
            contentsDiv.classList.remove('contents');
        }
        content = tempDiv.innerHTML;

        const categoryNamePostTitle = document.getElementById('categoryNamePostTitle');
        const categoryTitleInput = document.getElementById('categoryTitleInput');
        const categoryEditPostContentDiv = document.getElementById('categoryEditPostContentDiv');
        const categoryKindInput = document.getElementById('categoryKindInput');

        categoryNamePostTitle.value = name;
        categoryTitleInput.value = title;
        categoryEditPostContentDiv.innerHTML = content;
        categoryKindInput.value = kind;
    });
});

categoryEditModalSaveButton.addEventListener('click', function () {
    const newName = document.getElementById('categoryNamePostTitle').value;
    const newTitle = document.getElementById('categoryTitleInput').value;
    const newContent = document.getElementById('categoryEditPostContentDiv').innerHTML;
    const newKind = document.getElementById('categoryKindInput').value;

    // const categoryData = {
    //     id: currentCategoryId,
    //     name: newName,
    //     title: newTitle,
    //     content: newContent,
    //     kind: newKind
    // };
// 获取表单数据
    const formData = {
        name: document.getElementById('categoryNamePostTitle').value,
        title: document.getElementById('categoryTitleInput').value,
        content: document.getElementById('categoryEditPostContentDiv').innerHTML,
        kind: document.getElementById('categoryKindInput').value
    };
    console.log('currentCategoryId:', currentCategoryId);
    console.log('准备更新的类别ID:', currentCategoryId);
    console.log('更新的数据:', formData);

    // 发送AJAX请求
    $.ajax({
        url: `http://localhost:8080/admin/toUpdateCategory?id=${currentCategoryId}`,
        method: 'POST',
        data: formData,
        success: function(response) {
            console.log('服务器响应:', response);
            if (response.success) {
                // 先更新表格数据
                currentEditRow.querySelector('td:nth-child(2)').textContent = formData.name;
                currentEditRow.querySelector('td:nth-child(3)').textContent = formData.title;

                const contentCell = currentEditRow.querySelector('td:nth-child(4)');
                const contentDiv = document.createElement('div');
                contentDiv.classList.add('contents');
                contentDiv.innerHTML = formData.content;
                contentCell.innerHTML = contentDiv.outerHTML;

                currentEditRow.querySelector('td:nth-child(5)').textContent = formData.kind;

                // 隐藏模态框
                categoryEditModal.style.display = 'none';

                // 显示提示信息
                alert('类别更新成功'); // 用户点击确认后才会继续执行
            } else {
                alert('更新失败: ' + response.message);
            }
        },
        error: function(error) {
            console.error('AJAX请求错误:', error);
            alert('服务器错误，请稍后重试');
        }
    });
});

// 为所有取消按钮添加点击事件
const cancelEditPostButtons = document.querySelectorAll('.cancelEditPost');
cancelEditPostButtons.forEach(function (cancelEditPostButton) {
    cancelEditPostButton.addEventListener('click', function () {
        const modals = ['editModal', 'userEditModal', 'commentEditModal', 'categoryEditModal', 'reportEditModal'];
        modals.forEach(function (modalId) {
            const modal = document.getElementById(modalId);
            if (modal) {
                modal.style.display = 'none';
            }
        });
    });
    //添加
    const addButton2 = document.getElementById('addButton2');

    // 获取对应的模态框
    const addModal = document.getElementById('addModal');
    const addModal1 = document.getElementById('addModal1');
    const addModal2 = document.getElementById('addModal2');

    // 获取每个模态框的取消按钮

    const cancelButton2 = document.querySelector('.cancelEditPost2');

    // 为添加按钮添加点击事件监听器

    addButton2.addEventListener('click', function () {
        addModal2.style.display = 'block';
    });

});